<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddSubject">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="专题名称" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 专题管理table -->
    <el-table stripe :data="subjectTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef" @selection-change="handleSelectionChange">
      <el-table-column v-if="colData[0].istrue" prop="username" label="归属" min-width="110" align="center"></el-table-column>
      <el-table-column v-if="colData[1].istrue" prop="batch" label="SN码批次" min-width="150" align="center"></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="name" label="专题名称" min-width="150" align="center"></el-table-column>
      <el-table-column v-if="colData[3].istrue" label="专题图片" min-width="80" align="center">
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.img" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[4].istrue" prop="createtime" label="创建时间" min-width="140" align="center" sortable>
        <template slot-scope="scope">{{scope.row.createtime| newDate}}</template>
      </el-table-column>
      <!-- <el-table-column v-if="colData[4].istrue" label="专题状态" min-width="100" align="center">
        <template slot-scope="scope">
          <div class="state" :class="scope.row.status == 'normal' ? 'on_line' : 'off_line'">
            <i class="iconfont icon-dian1"></i>
            <span>{{scope.row.status == 'normal' ? '正常' : '离线'}}</span>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getquerySubjectId(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getdeleteSubject(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" :page-sizes="[10, 50, 100, 200]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 隐藏视图 -->
    <!-- 添加应用专题 -->
    <el-dialog :title="editSubjects ? '添加' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules">
        <el-form-item label="专题名称" label-width="100px" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入专题名称，最多为30位数" :maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="专题图片" label-width="100px" prop="img">
          <el-input v-model="addForm.img" v-if="false"></el-input>
          <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="iconAvatarSuccess">
            <div v-if="addForm.img" style="height:148px;width:148px">
              <img :src="addForm.img" class="avatar" style="height:100%;width:100%" />
            </div>
            <div v-else>
              <i class="el-icon-plus avatar-uploader-icon" style="height:148px;width:148px;line-height: 148px;background-color: #fbfdff;"></i>
            </div>
            <div style="color:#666;font-size:12px">建议分辨率940*410</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="SN码批次" label-width="100px" prop="batch">
          <el-select v-model="addForm.batch" placeholder="没有选中任何项" multiple class="wth_ato">
            <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="SN码状态：" label-width="100px">
          <el-radio v-model="addForm.status" label="normal">正常</el-radio>
          <el-radio v-model="addForm.status" label="hide">隐藏</el-radio>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="getaddSubject('ruleForm')" size="mini" round>确 定</el-button>
        <el-button v-else type="primary" @click="geteditSubject('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from '@/utils/objectable.js';
import { querySubject, uploadSubjectImg, addSubject, querySubjectId, editSubject, deleteSubject } from "@/api/application";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ['归属', 'SN码批次', '专题名称', '专题图片', '创建时间'],
      key: 1,
      colData: [],//动态控制table
      subjectTable: [],
      select: "", //搜索条件
      searchTable: "",
      total: 0, //总数量
      //添加表单
      addForm: { name: "", img: "", batch: '', status: "normal" },
      //批次下拉选择
      lotoptions: [],
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //编辑专题id
      subjectId: 0,
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        img: [{ required: true, message: "请上传图片", trigger: "blur" }],
        batch: [{ required: true, message: "请选择活动区域", trigger: "blur" }],
      },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, name: undefined, },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 }
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getquerySubject()
  },
  methods: {
    //删除
    getdeleteSubject(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      deleteSubject(params).then(res => {
        this.$message.success(res.msg)
        this.getquerySubject()
      }).catch(err => {
        console.log("请求失败删除单个专题", err);
      })
    },
    getquerySubject() {
      querySubject(this.listQuery).then(res => {
        this.subjectTable = res.data
        this.total = res.total
        console.log('请求成功', res.data)
      }).catch(err => {
        //this.$message.error(err.msg)
        this.subjectTable = []
        this.total = 0
      })
    },
    //搜索,1，专题名称
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.name = this.searchTable
          this.getquerySubject();
          break;
      }
    },
    //分页
    handleSizeChange(val) {
      //console.log("每页多少天", val);
      this.listQuery.pageSize = val
      this.getquerySubject();
    },
    handleCurrentChange(val) {
      //console.log("当前多少也", val);
      this.listQuery.startSize = val
      this.getquerySubject();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, name: undefined, }
      this.getquerySubject()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    //应用图标上传时的钩子
    iconAvatarSuccess(res, file) {
      //console.log('......', res.raw)
      let fd = new FormData();
      fd.append('file', res.raw);
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('userId', localStorage.getItem("ID"))
      uploadSubjectImg(fd).then(res => {
        console.log('图片上传', res)
        this.addForm.img = res.data.imgPath
      }).catch(err => {
        console.log("请求失败22", err);
      })
    },
    handleSelectionChange(val) {
      console.log('选择的专题', val)
    },
    btnaddSubject() {
      this.editSubjects = true
      this.dialogFormVisible = true
      this.getBatchTwos()
    },
    //添加专题
    getaddSubject(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addSubject(addForm).then(res => {
            this.$message.success(res.msg)
            this.getquerySubject()
            this.dialogFormVisible = false
          }).catch(err => {
            console.log("请求失败222", err);
          })
        } else {
          return false
        }
      })
    },
    //根据id查找专题信息
    getquerySubjectId(id) {
      this.editSubjects = false
      this.subjectId = id
      this.getBatchTwos()
      querySubjectId({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        this.addForm.name = data.name
        this.addForm.img = data.img
        this.addForm.status = data.status
        this.addForm.batch = data.batch.split(',')
      }).catch(err => {
        console.log("请求失败222", err);
      })
    },
    //编辑应用专题信息
    geteditSubject(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.id = this.subjectId
          editSubject(addForm).then(res => {
            this.$message.success(res.msg)
            this.getquerySubject()
            this.dialogFormVisible = false
          }).catch(err => {
            console.log("请求失败222", err);
          })
        } else {
          return false
        }
      })
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = {
          name: "",
          img: "",
          batch: '',
          status: "normal"
        }
      })
    },
  }
}
</script>
